package com.ease.integration.axis;

import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AxisTemplate {

	private static final transient Log log = LogFactory.getLog(AxisTemplate.class);

	protected String endpoint;

	@SuppressWarnings("unchecked")
	protected <T> T invoke(AxisServiceCallback<T> axisServiceCallback) {

		Service service = new Service();
		Call call;
		try {
			call = (Call) service.createCall();
			call.setTargetEndpointAddress(endpoint);
			call.setOperationName(axisServiceCallback.operationName());

			axisServiceCallback.addParameter(call);

			QName returnType = axisServiceCallback.returnType();
			if (null == returnType) {
				returnType = XMLType.XSD_STRING;
			}
			call.setReturnType(returnType);

			T returnValue = (T) call.invoke(axisServiceCallback.arguments());
			return returnValue;
		} catch (ServiceException e) {
			log.error(axisServiceCallback.operationName() + "@endpoint=" + endpoint, e);
		} catch (RemoteException e) {
			log.error(axisServiceCallback.operationName() + "@endpoint=" + endpoint, e);
		}

		return null;
	}

	/**
	 * @return the endpoint
	 */
	public String getEndpoint() {
		return endpoint;
	}

	/**
	 * @param endpoint
	 *            the endpoint to set
	 */
	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

}
